<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
      v-model="visibleDialog"
      :title="props.title"
      width="50%"
      draggable
      @close="closeDialog"
  >
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="数据库描述" prop="warehouseName">
            <el-input v-if="!props.isReadonly" v-model="formData.warehouseName" placeholder="请输入数据库描述"
                      clearable/>

            <span v-else>{{ formData.warehouseName }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="数据库编号" prop="warehouseCode">
            <el-input v-if="!props.isReadonly" v-model="formData.warehouseCode" placeholder="请输入数据库编号"
                      clearable/>

            <span v-else>{{ formData.warehouseCode }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="数据库类型" prop="jdbType">
            <el-select style="width: 100%;" v-if="!props.isReadonly" v-model="formData.jdbType"
                       placeholder="请选择数据库类型"
                       clearable @change="changeDataBaseType">
              <el-option key="mysql" label="mysql" value="mysql"/>
              <el-option key="postgresql" label="postgresql" value="postgresql"/>
              <!--              <el-option key="mongoDB" label="mongoDB" value="mongoDB"/>-->
            </el-select>

            <span v-else>{{ formData.jdbType }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="分层信息" prop="databaseLamination">
            <el-select style="width: 100%;" v-if="!props.isReadonly" v-model="formData.databaseLamination"
                       placeholder="请选择分层信息"
                       clearable>
              <el-option
                  v-for="item in dictionaryStore.filterDictList('DatabaseLamination')"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              />
            </el-select>
            <span v-else>{{ dictionaryStore.filterDictName('DatabaseLamination', formData.databaseLamination) }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="连接地址" prop="jdbcUrl">
        <el-input v-if="!props.isReadonly" v-model="formData.jdbcUrl" type="textarea" placeholder="请输入连接地址"
                  clearable/>
        <span v-else>{{ formData.jdbcUrl }}</span>
      </el-form-item>

      <el-row>
        <el-col :span="24">
          <el-form-item label="jdbc驱动类" prop="jdbcDriverClass">
            <el-input v-if="!props.isReadonly" v-model="formData.jdbcDriverClass" placeholder="请输入jdbc驱动类"
                      clearable/>
            <span v-else>{{ formData.jdbcDriverClass }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="用户名">
            <el-input v-if="!props.isReadonly" v-model="formData.jdbcUsername" placeholder="请输入用户名" clearable/>
            <span v-else>{{ formData.jdbcUsername }}</span>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="密码">
            <el-input v-if="!props.isReadonly" v-model="formData.jdbcPassword" type="password" placeholder="请输入密码"
                      clearable/>
            <span v-else>*******</span>
          </el-form-item>
        </el-col>
      </el-row>


      <el-form-item label="备注" prop="remarks">
        <el-input v-if="!props.isReadonly" v-model="formData.remarks" type="textarea" placeholder="请输入备注"
                  clearable/>
        <span v-else>{{ formData.remarks }}</span>
      </el-form-item>


    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button v-if="!props.isReadonly" type="primary" :loading="loading" @click="connectDataBase">测试连接
        </el-button>
        <el-button v-if="!props.isReadonly" type="primary" :loading="loading" @click="handleSubmit">确 定</el-button>
        <el-button @click="closeDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import {useDictStoreHook} from "@/store/modules/dictionary";
import {data} from "autoprefixer"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "DMPWAREHOUSEADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

const visibleDialog = ref(false);
watch(
    () => props.visible,
    (newVal: boolean) => {
      visibleDialog.value = newVal;
    }
);

const rules = reactive({
  warehouseName: [
    {required: true, message: "请输入数据库描述", trigger: "blur"},
    {min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur"}
  ],
  warehouseCode: [
    {required: true, message: "请输入数据库编号", trigger: "blur"},
    {min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur"}
  ],
  databaseLamination: [
    {required: true, message: "请选择分层信息", trigger: "blur"},
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
  jdbcUsername: [
    {required: true, message: "请输入用户名", trigger: "blur"},
    {min: 1, max: 100, message: "长度在 1 到 100 个字符", trigger: "blur"}
  ],
  jdbcPassword: [
    {required: true, message: "请输入密码", trigger: "blur"},
    {min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur"}
  ],
  jdbcUrl: [
    {required: true, message: "请输入连接地址", trigger: "blur"},
    {min: 1, max: 500, message: "长度在 1 到 500 个字符", trigger: "blur"}
  ],
  jdbType: [
    {required: true, message: "请选择数据库类型", trigger: "blur"},
    {min: 1, max: 20, message: "长度在 1 到 20 个字符", trigger: "blur"}
  ],
  jdbcDriverClass: [
    {required: true, message: "请输入jdbc驱动类", trigger: "blur"},
    {min: 1, max: 200, message: "长度在 1 到 200 个字符", trigger: "blur"}
  ],
  storageType: [],
  deleted: [],
  remarks: [
    {min: 1, max: 255, message: "长度在 1 到 255 个字符", trigger: "blur"}
  ],
});

const formRef = ref(ElForm);

let formData = reactive({
  id: "", warehouseName: "", warehouseCode: "", databaseLamination: "", jdbcUsername: "", jdbcPassword: "", jdbcUrl: "", jdbType: "", jdbcDriverClass: "", storageType: "", deleted: "", remarks: "", createdUserId: "", createTime: "", lastUpdatedUserId: "", createdUserName: "", lastUpdateTime: "", lastUpdatedUserName: "",
});

watch(
    () => props.data,
    (newVal: any) => {
      formData.id = ""
      if (newVal?.id) {
        const {id, warehouseName, warehouseCode, databaseLamination, jdbcUsername, jdbcPassword, jdbcUrl, jdbType, jdbcDriverClass, storageType, deleted, remarks, createdUserId, createTime, lastUpdatedUserId, createdUserName, lastUpdateTime, lastUpdatedUserName,} = newVal;
        Object.assign(formData, {id, warehouseName, warehouseCode, databaseLamination, jdbcUsername, jdbcPassword, jdbcUrl, jdbType, jdbcDriverClass, storageType, deleted, remarks, createdUserId, createTime, lastUpdatedUserId, createdUserName, lastUpdateTime, lastUpdatedUserName,});
      }
    }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.id = ""
  formData.warehouseName = ""
  formData.warehouseCode = ""
  formData.databaseLamination = ""
  formData.jdbcUsername = ""
  formData.jdbcPassword = ""
  formData.jdbcUrl = ""
  formData.jdbType = ""
  formData.jdbcDriverClass = ""
  formData.storageType = ""
  formData.deleted = ""
  formData.remarks = ""
  formData.createdUserId = ""
  formData.createTime = ""
  formData.lastUpdatedUserId = ""
  formData.createdUserName = ""
  formData.lastUpdateTime = ""
  formData.lastUpdatedUserName = ""
}

const loading = ref(false);

/** 数据仓库保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: "/dmpAdmin/dmpwarehouse/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
    }
  });
}


// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

/**
 * 数据库类型切换
 * */
function changeDataBaseType(type) {

  formData.storageType = ""
  formData.jdbcUrl = ""
  formData.jdbcDriverClass = ""

  // 数据库类型
  if (type == "mysql") {
    formData.storageType = 1
    formData.jdbcUrl = "jdbc:mysql://{host}:{port}/{database}"
    formData.jdbcDriverClass = "com.mysql.jdbc.Driver"
  }

  // 数据库类型
  if (type == "postgresql") {
    formData.storageType = 1
    formData.jdbcUrl = "jdbc:postgresql://{host}:{port}/{database}"
    formData.jdbcDriverClass = "org.postgresql.Driver"
  }

  // 数据库类型
  if (type == "mongoDB") {
    formData.storageType = 2
    formData.jdbcUrl = "mongodb://{username}:{password}@{host}:{port}/{database}"
  }
}

/**
 * 测试连接数据库
 * */
function connectDataBase() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      request({
        url: "/dmpAdmin/dmpwarehouse/database/check",
        method: "post",
        data: formData,
      }).then(rep => {
        ElMessage.success(`数据库连接成功`);
      }).finally(() => {
        loading.value = false;
      });
    }
  });
}
</script>
